package es.sergionadal.mvc.bbdd.tablas;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import es.sergionadal.mvc.bbdd.util.CreateSentenciaString;
import es.sergionadal.mvc.vo.CampoVO;
import es.sergionadal.mvc.vo.ForeignKeyVO;

public abstract class Tabla {
	private String name;

	private List<CampoVO> campos;

	private String sqlCreate;

	private String sqlDrop;

	public static final String ID = "id";

	public String getSqlDrop() {
		return sqlDrop;
	}

	public String getSqlCreate() {
		return sqlCreate;
	}

	public String getName() {
		return name;
	}

	public List<CampoVO> getCampos() {
		return campos;
	}

	public Tabla(String name) {
		super();
		this.name = name;
	}

	public void create(ListTablas listTablas) {
		campos = getCamposChild();
		sqlCreate = CreateSentenciaString.createTable(this, listTablas);
		sqlDrop = CreateSentenciaString.createDropTable(this);
	}

	abstract protected List<CampoVO> getCamposChild();

	abstract public long insert(SQLiteDatabase db);

	abstract public void update(SQLiteDatabase db, String[] args);

	public ArrayList<ForeignKeyVO> getForeignKey(ListTablas tablas) {
		return null;
	}

	public CampoVO getId() {
		return new CampoVO(ID, CampoVO.INTEGER, CampoVO.CONSTRAINT_PK);
	}

	public String getParameterField(String fieldName) {
		return fieldName.concat(" = ?");
	}

	public void delete(SQLiteDatabase db, String[] args) {
		db.delete(getName(), getParameterField(ID), args);
	}

	protected String[] getColumns() {
		List<CampoVO> campos = getCamposChild();
		String[] columns = new String[campos.size()];
		for (int i = 0; i < campos.size(); i++) {
			columns[i] = campos.get(i).getNombreParametro();
		}
		return columns;
	}

	protected Cursor getAll(SQLiteDatabase db) {
		return db.query(getName(), getColumns(), null, null, null, null, ID);
	}

	protected Cursor getRegistroPerID(SQLiteDatabase db, String id) {
		return db.query(getName(), getColumns(), getParameterField(ID),
				new String[] { id }, null, null, ID);
	}

}
